package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasListGroupEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.model.PaasListGroupModel;
import com.xbongbong.paas.pojo.SaveConfigDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.domain.entity.DetailTabConfigEntity;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.script.pojo.vo.ScriptVO;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.model.DetailTabConfigModel;
import com.xbongbong.sys.domain.entity.UserConfigEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.UserConfigEnum;
import com.xbongbong.sys.model.UserConfigModel;
import com.xbongbong.sys.model.UserModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2023/04/06 16:38
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/config")
@Slf4j
public class UserConfigScriptController {

    @Resource
    private UserConfigModel userConfigModel;
    @Resource
    private PaasListGroupModel paasListGroupModel;
    @Resource
    private DetailTabConfigModel detailTabConfigModel;
    @Resource
    private UserModel userModel;
    @Resource
    private ProBaseConfig proBaseConfig;

    @RequestMapping(value = "/saveUserConfig", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String contractMaintenance(@RequestBody @Valid SaveConfigDTO saveConfigDTO, BindingResult br) throws XbbException {
        if (!proBaseConfig.getXbbCode().equals(saveConfigDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        XbbResponse<ScriptVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ScriptVO scriptVO = new ScriptVO();

                saveUserConfig(saveConfigDTO);
                response = new XbbResponse<>(scriptVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    private void saveUserConfig(SaveConfigDTO saveConfigDTO) throws XbbException{

        if (CollectionUtils.isEmpty(saveConfigDTO.getConfigAlias())) {
            return;
        }
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("configAliasIn", saveConfigDTO.getConfigAlias());
        params.put("userId", saveConfigDTO.getUserId());
        params.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        params.put(StringConstant.CORPID, saveConfigDTO.getCorpid());
        List<UserConfigEntity> userConfigList = userConfigModel.list(params);
        String key = saveConfigDTO.getAppId() + "_" + saveConfigDTO.getFormId();
        Map<String, Object> param = new HashMap<>();
        param.put(StringConstant.CORPID, saveConfigDTO.getCorpid());
        param.put(StringConstant.DEL, 0);
        List<UserEntity> userList = userModel.findEntitys(param);
        int count = userList.size();
        int i= 0;
        for (UserEntity item : userList) {
            if (Objects.equals(item.getUserId(), saveConfigDTO.getUserId())) {
                continue;
            }
            userConfigList.forEach(userConfigEntity -> {
                String[] configAliasArray = userConfigEntity.getConfigAlias().split("_");
                String configAlias = configAliasArray[0];
                if (Objects.equals(configAlias, UserConfigEnum.FORM_COMMON_FILTER.getAlias())) {
                    configAlias = configAlias + "_" + userConfigEntity.getCorpid() + "_" + key + "_" + item.getUserId();
                } else {
                    configAlias = configAlias + "_" + key;
                }
                userConfigEntity.setId(null);
                userConfigEntity.setConfigAlias(configAlias);
                userConfigEntity.setUserId(item.getUserId());
            });
            userConfigModel.insertBatch(userConfigList);
            i++;
            log.info("total：" + count + "》" + i);
        }
    }

    @RequestMapping(value = "/saveGroupListConfig", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String saveGroupListConfig(@RequestBody @Valid SaveConfigDTO saveConfigDTO, BindingResult br) throws XbbException {
        if (!proBaseConfig.getXbbCode().equals(saveConfigDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        XbbResponse<ScriptVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ScriptVO scriptVO = new ScriptVO();
                saveGroupListConfig(saveConfigDTO);
                response = new XbbResponse<>(scriptVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }


    private void saveGroupListConfig(SaveConfigDTO saveConfigDTO) throws XbbException {
        String corpid = saveConfigDTO.getCorpid();
        List<PaasListGroupEntity> list = paasListGroupModel.listByUserId(saveConfigDTO.getCorpid(), saveConfigDTO.getAppId(),
                saveConfigDTO.getFormId(), saveConfigDTO.getUserId(), " sort asc ");
        Map<String, Object> param = new HashMap<>();
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, 0);
        List<UserEntity> userList = userModel.findEntitys(param);
        int count = userList.size();
        int i= 0;
        for (UserEntity item : userList) {
            List<PaasListGroupEntity> insertList = new ArrayList<>();
            if (Objects.equals(item.getUserId(), saveConfigDTO.getUserId())) {
                continue;
            }
            list.forEach(paasListGroupEntity -> {
                paasListGroupEntity.setId(null);
                paasListGroupEntity.setCreatorId(item.getUserId());
                insertList.add(paasListGroupEntity);
            });
            paasListGroupModel.insertBatch(insertList);
            i++;
            log.info("total：" + count + "》" + i);
        }
    }

    @RequestMapping(value = "/saveDetailTabConfig", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String saveDetailTabConfig(@RequestBody @Valid SaveConfigDTO saveConfigDTO, BindingResult br) throws XbbException {
        if (!proBaseConfig.getXbbCode().equals(saveConfigDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        XbbResponse<ScriptVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ScriptVO scriptVO = new ScriptVO();
                saveDetailTabConfig(saveConfigDTO);
                response = new XbbResponse<>(scriptVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    private void saveDetailTabConfig(SaveConfigDTO saveConfigDTO) throws XbbException {
        String corpid = saveConfigDTO.getCorpid();
        DetailTabConfigEntity detailTabConfigEntity = detailTabConfigModel.getEntityByBusinessTypeAndFormId(corpid, saveConfigDTO.getUserId(), saveConfigDTO.getBusinessType(), saveConfigDTO.getFormId());
        Map<String, Object> param = new HashMap<>();
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, 0);
        List<UserEntity> userList = userModel.findEntitys(param);
        List<DetailTabConfigEntity> insertList = new ArrayList<>();

        if (Objects.nonNull(detailTabConfigEntity)) {
            userList.forEach(item->{
                if (Objects.equals(item.getUserId(), saveConfigDTO.getUserId())) {
                    return;
                }
                DetailTabConfigEntity insert = new DetailTabConfigEntity();
                BeanUtil.copyProperties(detailTabConfigEntity, insert);
                insert.setId(null);
                insert.setUserId(item.getUserId());
                insert.setCreatorId(item.getUserId());
                insertList.add(insert);
            });
            detailTabConfigModel.insertBatch(insertList);
        }
        log.info("已执行总数：" + insertList.size());

    }
}
